import { defineStore } from 'pinia'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

export const useTreeStore = defineStore('tree', {
    state: () => ({
        baseTree: null,
        isSearch: false,
        searchParam: ""
    }),
    actions: {
        async loadTreeData(searchParam, apiError = false) {
            console.log(apiError)
            this.searchParam = searchParam
            if (searchParam) {
                this.isSearch = true
            }
            const { data } = await request.post('/zhsj/api/getfirestfloor2', {}, { "params": searchParam })

            if (!data) {
                this.baseTree = []
                if (searchParam.proname) {
                    ElMessage.error("没有上传该项目信息")
                    return false
                }
                return
            }
            
            this.baseTree = data.map((item) => ({
                id: item.id,
                label: item.typname,
                children: item.dqchildren
                    // 当 apiError 为 true 时，过滤 dqchildren
                    .filter(dq => !apiError || dq.typname === searchParam.qu)
                    .map((_item) => ({
                        id: _item.id,
                        label: _item.typname,
                        isDq: true,
                        children: _item.prochildren.map((__item) => ({
                            id: __item.id,
                            label: `${__item.proname}`,
                            proid: __item.proidstr,
                            appendData: __item
                        }))
                    }))
            }))
        },
        async loadNodeChildren(node) {
            // 这里添加加载子节点的逻辑
            console.log('Loading children for node:', node)
            // 示例：
            // const { data } = await request.post('/zhsj/api/getChildNodes', { parentId: node.id })
            // return data.map(item => ({ id: item.id, label: item.name, children: [] }))
        }
    }
})
